import random
from selenium import webdriver
import time
from selenium.webdriver import ActionChains
from chaojiying import Chaojiying_Client
from PIL import Image
from fake_useragent import UserAgent


class Zlzp:
    '''浏览器对象'''
    def __init__(self, name, password):
        self.options = webdriver.ChromeOptions()
        self.options.add_argument('user-agent="%s"' % (str(UserAgent().random)))
        # self.options.add_argument('--headless')
        self.name = name
        self.password = password
        self.driver = webdriver.Chrome(chrome_options=self.options)

    def get_cookies(self):
        self.driver.get('https://passport.zhaopin.com/org/login')
        time.sleep(1)
        # 输入信息
        self.driver.find_element_by_id('loginName').clear()
        self.driver.find_element_by_id('loginName').send_keys(name)
        time.sleep(0.3)
        self.driver.find_element_by_name('password').clear()
        self.driver.find_element_by_name('password').send_keys(password)
        time.sleep(0.3)
        self.driver.find_element_by_id('loginbutton').click()
        time.sleep(2)
        # 获取图片
        while 1:
            try:
                logo = self.driver.find_element_by_xpath("//div[@class='geetest_widget']")
                logo.screenshot('img.png')
                img = Image.open('img.png')
                box = (0, 0, 320, 360)
                img1 = img.crop(box)
                img1.save('img.png')

                # self.driver.close()
                # 调用接口
                chaojiying = Chaojiying_Client('masiwen', 'yanzhengma', '897910')
                im = open('img.png', 'rb').read()
                xy = chaojiying.PostPic(im, 9004)
                print(xy)
                locations = xy["pic_str"].split("|")
                # 找到那个图片的坐标(左上角的坐标)
                for location in locations:
                    print('locations ',locations)
                    print('没s',location)
                    x, y = location.split(",")
                    ActionChains(self.driver).move_to_element_with_offset(logo, xoffset=int(x), yoffset=int(y)).click().perform()
                    time.sleep(random.randint(20, 30)/10)
                self.driver.find_element_by_xpath("/html/body/div[2]/div[2]/div[6]/div/div/div[3]/a/div").click()
                time.sleep(random.randint(20, 30) / 10)
                print('获取失败')
            except:
                break
        print('获取成功')
        return self.driver.get_cookies()

if __name__ == '__main__':
    name = 'jucailin03'
    password = 'jucailin03'
    dajie = Zlzp(name, password)
    print(dajie.get_cookies())